<template>
  <div id="campusAreaDiv">
    <Breadcrumb content="院区管理" />
    <div class="bodyContent">
      <Splitpanes>
        <Pane size="50">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input style="width: 180px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="getCampusAreaList" @keyup="keyupEnter" @search-click="getCampusAreaList()"></vxe-input>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="tloading" @click="getCampusAreaList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addCampusAreaDialog()"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteCampusArea"></vxe-button>

            </template>
          </vxe-toolbar>

          <div class="tableBody">
            <vxe-table ref="campusAreaTableRef" class="mytable-scrollbar" border="inner" align="center" height="auto" :data="campusAreaList" :loading="tloading" @current-change="campusAreaRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
              <vxe-column type='checkbox' width='30px'></vxe-column>
              <vxe-column field='campusCode' title='编码'></vxe-column>
              <vxe-column field='campusName' title='名称'></vxe-column>
              <vxe-column field="inputCode" title="助记符"> </vxe-column>
              <vxe-column field="contactName" title="联系人"> </vxe-column>
              <vxe-column field="contactTel" title="联系电话"> </vxe-column>
              <vxe-column field="address" title="地址" min-width="110"></vxe-column>
              <vxe-column field='seq' title='顺序'></vxe-column>
            </vxe-table>
            <vxe-pager align="left" min-height="32px" :current-page.sync="page.currentPage" :page-size.sync="page.pageSize" :total="page.totalResult" :layouts="[
                'PrevJump',
                'PrevPage',
                'Number',
                'NextPage',
                'NextJump',
                'Sizes',
                'FullJump',
                'Total'
              ]" @page-change="handleSizeChange($event)"></vxe-pager>
          </div>
        </Pane>
        <Pane size="50">
          <el-tabs type="border-card" v-model="activeName" @tab-click="tabHandleClick">
            <el-tab-pane label="基础信息" name="first">
              <vxe-toolbar perfect>
                <template #buttons>
                  <vxe-button type="text" class="button-blue" @click="saveCampusArea('campusAreaFormRef')" icon="vxe-icon-square-plus" content="保存"></vxe-button>
                </template>
              </vxe-toolbar>
              <el-form ref="campusAreaFormRef" :model="campusAreaForm" :rules="campusAreaFormRule" class="form-input-m" label-width="100px" inline-message>
                <el-row :gutter='20'>
                  <el-col :span='12'>
                    <el-form-item label='编码' prop='campusCode'>
                      <el-input v-model='campusAreaForm.campusCode' placeholder='请输入编码' clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span='12'>
                    <el-form-item label='名称' prop='campusName'>
                      <el-input v-model='campusAreaForm.campusName' placeholder='请输入名称' clearable @blur="addInputCode()"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter='20'>
                  <el-col :span='12'>
                    <el-form-item label='联系人' prop='contactName'>
                      <el-input v-model='campusAreaForm.contactName' placeholder='请输入联系人' clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span='12'>
                    <el-form-item label='输入码' prop='inputCode'>
                      <el-input v-model='campusAreaForm.inputCode' placeholder='请输入输入码' clearable></el-input>
                    </el-form-item>
                  </el-col>

                </el-row>
                <el-row :gutter='20'>
                  <el-col :span='12'>
                    <el-form-item label='联系电话' prop='contactTel'>
                      <el-input v-model='campusAreaForm.contactTel' placeholder='请输入联系电话' clearable @blur="addInputCode()"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span='12'>
                    <el-form-item label='地址' prop='address'>
                      <el-input v-model='campusAreaForm.address' placeholder='请输入地址' clearable></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter='20'>
                  <el-col :span='12'>
                    <el-form-item label='顺序' prop='seq'>
                      <el-input-number v-model="campusAreaForm.seq" :min="1" :max="10000" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="报告单元" name="second" :disabled="isEmpty(campusAreaForm.id)">
              <LabRptCampusArea ref="labRptCampusRef" />
            </el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { isEmpty } from 'lodash';
import { funBdsJsResult } from '@/utils/Expression'; //函数公式
import Breadcrumb from '@/components/Breadcrumb.vue';
import LabRptCampusArea from '@/views/lab_sys/lab_set/LabRptCampusArea.vue'; //失控记录图表

let labRptCampusRef: any = ref(null);

let searchForm = {
  searchValue: ''
};
let tloading = ref(false); //加载状态
let activeName = ref('first');
let campusAreaList: any = reactive([]);
let sltCampusArea: any = ref({});
// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
// 分页
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});

let campusAreaForm = reactive({
  id: null,
  campusCode: '' /*编码*/,
  campusName: '' /*名称*/,
  contactName: '' /*联系人*/,
  contactTel: '' /*联系电话*/,
  address: '' /*地址*/,
  inputCode: '',
  seq: 1 /*显示顺序*/
});

let campusAreaFormRule = {
  campusName: [
    {
      required: true,
      message: '请输入名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ],
  campusCode: [
    {
      required: true,
      message: '请输入编码',
      trigger: 'blur'
    }
  ]
};
onMounted(() => {
  getDictItemsList();
  getCampusAreaList();
});

let instrClassDict = reactive([]); //仪器大类字典
let workGroupList = reactive([]); //仪器大类字典

//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['YQDL', 'JYGZZ'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const maintainTypes = dictTreeTypeItems.data.find((item) => item.code === 'YQDL');
  instrClassDict.push(...maintainTypes.detailDataList);
  const maintainStatues = dictTreeTypeItems.data.find((item) => item.code === 'JYGZZ');
  workGroupList.push(...maintainStatues.detailDataList);
}

function getCampusAreaList() {
  tloading.value = true;
  campusAreaList.length = 0; //放入数据前清空数据
  const url = '/api/sys/campusArea/findCampusAreaPageList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        seachValue: searchForm.searchValue,
        pageIndex: page.currentPage,
        pageSize: page.pageSize
      }
    })
    .then((res: any) => {
      campusAreaList.push(...res.data.records);
      page.totalResult = res.data.total;
      const kn = campusAreaList.find((k) => k.id == sltCampusArea.value.id);
      if (isEmpty(kn)) {
        campusAreaRowClick({ row: campusAreaList[0] }); //默认选中第一条数据
      } else {
        campusAreaRowClick({ row: kn }); //默认选中第一条数据
      }
      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

//点击每页数量(分页查询)
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  getCampusAreaList();
}

function saveCampusArea(formName: any) {
  let $el = proxy.$refs[formName];
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    if (campusAreaForm.id === null) {
      const url = '/api/sys/campusArea/addCampusArea';

      proxy.$http
        .post(url, campusAreaForm)
        .then((res: any) => {
          VxeMessage('新增成功', VxeNotifyType.success);
          clearForm();
          sltCampusArea.value.id = res.data.id;
          getCampusAreaList();
        })
        .catch((err: any) => {
          VxeMessage('新增失败', VxeNotifyType.error);
        });
    } else {
      // 修改用户
      const url = '/api/sys/campusArea/editCampusArea';

      proxy.$http
        .post(url, campusAreaForm)
        .then((res: any) => {
          VxeMessage('修改成功', VxeNotifyType.success);
          sltCampusArea.value.id = res.data.id;
          setTimeout(() => {
            clearForm();
            getCampusAreaList();
          }, 50);
        })
        .catch((err: any) => {
          VxeMessage('修改失败', VxeNotifyType.error);
        });
    }
  });
}
function deleteCampusArea() {
  const sltCampusAreas = (proxy.$refs.campusAreaTableRef as any).getCheckboxRecords();
  if (!(sltCampusAreas.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delCampusAreaList = sltCampusAreas.filter((p: any) => !isEmpty(p.id));
        if (delCampusAreaList.length > 0) {
          const data = { campusAreaList: delCampusAreaList };
          const url = '/api/sys/campusArea/batchDeleteCampusArea';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              getCampusAreaList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}
// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    getCampusAreaList();
  }
}
// 点击设计模式表格当前行触发右侧表单变化
function campusAreaRowClick({ row }: any) {
  if (isEmpty(row)) {
    clearForm();
    sltCampusArea.value = {};
  } else {
    (proxy.$refs.campusAreaTableRef as any).setCurrentRow(row);
    setCampusAreaForm(row);
    if (activeName.value == 'second') {
      labRptCampusRef.value.initPage(row);
    }
  }
}

function addCampusAreaDialog() {
  clearForm();
  sltCampusArea.value = {};
  (proxy.$refs.campusAreaTableRef as any).clearCurrentRow();
  activeName.value = 'first';
}

// 清空中间规则弹框表单
function clearForm() {
  for (let key in campusAreaForm) {
    campusAreaForm[key] = '';
  }
  campusAreaForm.id = null;
  campusAreaForm.seq = 1;
}

// 编辑当前行规则
function setCampusAreaForm(row: any) {
  if (row !== null) {
    for (let prop in row) {
      campusAreaForm[prop] = row[prop];
    }
  }
  sltCampusArea.value = row;
}

function tabHandleClick(tab: any) {
  if (tab.props.name == 'second') {
    labRptCampusRef.value.initPage(sltCampusArea.value);
  }
}

// 填写仪器名称 自动生成助记符
function addInputCode() {
  campusAreaForm.inputCode = funBdsJsResult('firstPinYinFun', campusAreaForm.campusName);
}
const predefineColors = ref(['#ff4500', '#ff8c00', '#ffd700', '#90ee90', '#00ced1', '#1e90ff', '#c71585', 'rgba(255, 69, 0, 0.68)', 'rgb(255, 120, 0)', 'hsv(51, 100, 98)', 'hsva(120, 40, 94, 0.5)', 'hsl(181, 100%, 37%)', 'hsla(209, 100%, 56%, 0.73)', '#c7158577']);
</script>

<style lang="scss" scoped>
#campusAreaDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .tableBody {
        height: calc(100% - 40px - 32px);
      }
      .el-tabs {
        height: 100%;
        :deep(.el-tabs__content) {
          height: calc(100% - 40px - 30px);
          .el-tab-pane {
            height: 100%;
          }
        }
      }
    }
  }
}
</style>